package org.rxc.auth.controller;

import org.rxc.auth.context.LoginContext;
import org.rxc.auth.dto.LoginDto;
import org.rxc.base.utils.AjaxResult;
import org.rxc.org.domain.Employee;
import org.rxc.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/login")
public class AuthController {
    @Autowired
    private IEmployeeService employeeService;
    @PostMapping
    public AjaxResult login(@RequestBody LoginDto loginDto){
       Employee employee =  employeeService.queryByUsername(loginDto.getUsername());
       if (employee!=null){
           if (employee.getPassword().equals(loginDto.getPassword())){
               //登录成功
               //生成token(唯一不重复)
               String token = UUID.randomUUID().toString();
               //做脱敏处理
               employee.setPassword("");
               //往全局map里存放数据
               LoginContext.context.put(token,employee);
               Map<String,Object> map = new HashMap<>();
               map.put("token",token);
               map.put("user",employee);
               return AjaxResult.me().setData(map);
           }else {
               //登录失败
               return AjaxResult.me().setSuccess(false).setMsg("用户名或密码错误");
           }
       }else {
           //登录失败
           return AjaxResult.me().setSuccess(false).setMsg("用户名或密码错误");
       }
    }
}
